package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	private CustomerRepository customerRepository;
	//未关联的客户
	@Override
	public List<Customer> findNoAssociationCustomers() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	//已经和定区关联的用户
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(
			String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	//将客户定区进行关联
	@Override
	public void associationCustomersToFixedArea(String customerIdStr,
			String fixedAreaId) {
		//进行关联之前先解除关联
		customerRepository.clearFixedAeraId(fixedAreaId);
		//档CustomerIdStr为空时，就结束
		if ("null".equals(customerIdStr)||StringUtils.isEmpty(customerIdStr)) {
			
			return ;
		}
		//customerIdStr是多个客户id用逗号拼成的字符串
		String[] idStr = customerIdStr.split(",");
		for (String string : idStr) {
			//修改客户id的fixedAreaid
			Integer id=Integer.parseInt(string);
			customerRepository.updateFixedAreaId(fixedAreaId,id);
		}
	}

	@Override
	public void regist(Customer customer) {
		 customerRepository.save(customer);
	}

	@Override
	public Customer findByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}

}
